package apps.sim.util.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

public abstract class CallableTask<T> implements Callable<T> {
	private CountDownLatch latch;

	public void setLatch(CountDownLatch latch) {
		this.latch = latch;
	}

	public CountDownLatch getLatch() {
		return latch;
	}

	@Override
	public T call() throws Exception {
		try {
			return execute();
		} finally {
			latch.countDown();
		}
	}

	protected abstract T execute() throws Exception;

	public static abstract class NoResponseCallableTask extends CallableTask<Void> {
		private CountDownLatch latch;

		public void setLatch(CountDownLatch latch) {
			this.latch = latch;
		}

		public CountDownLatch getLatch() {
			return latch;
		}

		@Override
		public Void call() throws Exception {
			try {
				execute();
			} finally {
				latch.countDown();
			}
			return null;
		}
	}

}
